<template>
<div class="tab-pane active" id="nvs-config">
  <form class="form-horizontal" autocomplete="off" spellcheck="false" @submit.prevent="onNVSSubmit" data-vv-scope="nvs">
    <div :class="['form-group' , {'has-error': errors.has('nvs.ip')}]">
      <label for="nvs-ip" class="col-sm-3 control-label">服务 IP</label>
      <div class="col-sm-8">
        <input type="text" id="nvs-ip" class="form-control" name="ip" data-vv-as="服务 IP" v-model.trim="IP">
        <!-- <span class="help-block">{{errors.first('nvs.ip')}}</span> -->
      </div>
    </div>
    <div :class="['form-group' , {'has-error': errors.has('nvs.port')}]">
      <label for="nvs-port" class="col-sm-3 control-label">服务端口</label>
      <div class="col-sm-8">
        <input type="text" id="nvs-port" class="form-control" name="port" data-vv-as="服务端口" v-validate="'numeric'" v-model.trim="Port">
        <!-- <span class="help-block">{{errors.first('nvs.port')}}</span> -->
      </div>
    </div>
    <div :class="['form-group' , {'has-error': errors.has('nvs.bind_local_port')}]">
      <label for="nvs-bind-local-port" class="col-sm-3 control-label">本地端口</label>
      <div class="col-sm-8">
        <input type="text" id="nvs-bind-local-port" class="form-control" name="bind_local_port" data-vv-as="本地端口" v-validate="'numeric'" v-model.trim="BindLocalPort" placeholder="可选">
        <!-- <span class="help-block">{{errors.first('nvs.bind_local_port')}}</span> -->
      </div>
    </div>
    <div :class="['form-group' , {'has-error': errors.has('nvs.serial')}]">
      <label for="nvs-uid" class="col-sm-3 control-label">设备序列号</label>
      <div class="col-sm-8">
        <input type="text" id="nvs-uid" class="form-control" name="serial" data-vv-as="设备序列号" v-validate="'alpha_dash'" v-model.trim="UID">
        <!-- <span class="help-block">{{errors.first('nvs.serial')}}</span> -->
      </div>
    </div>
    <div :class="['form-group' , {'has-error': errors.has('nvs.name')}]">
      <label for="nvs-name" class="col-sm-3 control-label">设备名称</label>
      <div class="col-sm-8">
        <input type="text" id="nvs-name" class="form-control" name="name" data-vv-as="设备名称" v-model.trim="UName">
        <!-- <span class="help-block">{{errors.first('nvs.name')}}</span> -->
      </div>
    </div>
    <div :class="['form-group' , {'has-error': errors.has('nvs.token')}]">
      <label for="nvs-token" class="col-sm-3 control-label">接入密码</label>
      <div class="col-sm-8">
        <div class="input-group">
          <input type="text" id="nvs-token" class="form-control" name="token" data-vv-as="接入密码" v-model.trim="Token" v-if="rawPwd">
          <input type="password" id="nvs-token" class="form-control" name="token" autocomplete="new-password" data-vv-as="接入密码" v-model.trim="Token" v-else
            onfocus="this.readOnly = false;" onblur="this.readOnly = true;" style="background-color: #FFF;" readonly>
          <span class="input-group-btn">
              <button type="button" class="btn btn-default" @click="rawPwd = !rawPwd;" style="border-top-right-radius:0;border-bottom-right-radius:0;">
                  <i class="glyphicon glyphicon-eye-open" v-if="rawPwd"></i>
                  <i class="glyphicon glyphicon-eye-close" v-else></i>
              </button>
          </span>
        </div>
        <!-- <span class="help-block">{{errors.first('nvs.token')}}</span> -->
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-offset-3 col-sm-8 checkbox">
        <el-checkbox id="nvs-enable" style="margin-left:-19px;margin-top:-5px;" size="small" v-model.trim="Enable" name="Enable">
          启用级联
        </el-checkbox>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <button type="submit" class="btn btn-primary" :disabled="isNVSNoChange || errors.any('nvs') || bCommitting">保存</button>
      </div>
    </div>
    <div :class="['form-group' , {'has-error': Status && Status != 'Running', 'has-success': Status && Status == 'Running'}]">
      <div class="col-sm-offset-3 col-sm-8">
        <span class="help-block">{{Status}}&nbsp;</span>
      </div>
    </div>
  </form>
</div>
</template>

<script>
import $ from "jquery";
export default {
  data() {
    return {
      bCommitting: false,
      UID: "", //设备序列码
      UName: "", //设备名称
      Token: "", //设备码
      Port: 0, //监听端口
      BindLocalPort: "",
      IP: "", //IP地址
      Status: "",
      Enable: false,
      rawPwd: true,
      remoteNVSData: "",
      timer: 0
    };
  },
  mounted() {
    this.getNVSConfig()
    this.timer = setInterval(() => {
      this.getNVSConfig(true);
    }, 2000);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = 0;
    }
  },
  methods: {
    async onNVSSubmit() {
      var ok = await this.$validator.validateAll('nvs');
      if (!ok) {
        var e = this.errors.items[0];
        this.$message({
          type: "error",
          message: e.msg
        });
        $(`[name=${e.field}]`).focus();
        return;
      }
      this.bCommitting = true;
      $.get("/api/v1/setnvsconfig", this.getNVSCommitObject()).then(data => {
        if ((data.LiveQing || data.NVR).Header.ErrorNum == 200) {
          this.$message({
            type: "success",
            message: "配置成功！"
          });
          this.getNVSConfig();
        } else {
          this.$message({
            type: "error",
            message: "配置失败！"
          });
        }
      }).always(() => {
        this.bCommitting = false;
      })
    },
    getNVSCommitObject() {
      return {
        UID: this.UID,
        UName: this.UName,
        Token: this.Token,
        Port: this.Port,
        BindLocalPort: this.BindLocalPort,
        IP: this.IP,
        Enable: this.Enable,
      };
    },
    getNVSConfig(statusOnly) {
      $.get("/api/v1/getnvsconfig").then(data => {
        var body = (data.LiveQing || data.NVR).Body;
        if (!body) return;
        this.Status = body.Status || "";
        if (statusOnly) {
          return
        }
        this.UName = body.UName || "";
        this.UID = body.UID || "";
        this.Port = body.Port || "";
        this.BindLocalPort = body.BindLocalPort || "";
        this.IP = body.IP || "";
        this.Enable = !!body.Enable;

        setTimeout(() => {
          this.Token = body.Token || "";
          this.rawPwd = false;
          this.remoteNVSData = JSON.stringify(this.getNVSCommitObject());
        }, 300);
      });
    }
  },
  computed: {
    isNVSNoChange() {
      var localeData = JSON.stringify(this.getNVSCommitObject());
      return this.remoteNVSData.localeCompare(localeData) == 0;
    }
  }
};
</script>
